package com.fun.feifun.modules.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fun.feifun.base.utils.ControlUtils;
import com.fun.feifun.base.utils.RedisUtil;
import com.fun.feifun.base.utils.format.FormatUtil;
import com.fun.feifun.modules.business.model.BusinessGoods;
import com.fun.feifun.modules.business.model.BusinessOrder;
import com.fun.feifun.modules.business.model.BusinessUser;
import com.fun.feifun.modules.business.model.param.BusinessPlaceOrderParam;
import com.fun.feifun.modules.business.service.*;
import com.fun.feifun.modules.sys.parameter.service.ISysParameterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 * 业务供应商 前端控制器
 * </p>
 *
 * @author wkf
 * @since 2024-06-04
 */
@RestController
@Api(value = "/business/user-api-new", tags = "API-用户")
@Slf4j
@RequestMapping("/business/user-api-new")
public class BusinessUserAPINewController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IBusinessOrderService service;
    @Autowired
    private IBusinessUserService businessUserService;
    @Autowired
    private IBusinessSupplierService supplierService;
    @Autowired
    private IBusinessGoodsService businessGoodsService;
    @Autowired
    private IBusinessUserGoodsService userGoodsService;
    @Autowired
    private IBusinessUserService userService;
    @Autowired
    private ISysParameterService parameterService;
    @Autowired
    private IBusinessOrderLogService logService;
    @Autowired
    private IBusinessBlacklistService blacklistService;

    @Resource
    private RedisUtil redisUtil;


    @PostMapping(value = "/placeOrderOutside")
    @ApiOperation(value = "用户-话费订单提交接口")
    public String placeOrder(@RequestParam(value = "userid") String userid,
                             @RequestParam(value = "productid") String productid,
                             @RequestParam(value = "price") Integer price,
                             @RequestParam(value = "num") Integer num,
                             @RequestParam(value = "mobile") String mobile,
                             @RequestParam(value = "spordertime") String spordertime,
                             @RequestParam(value = "sporderid") String sporderid,
                             @RequestParam(value = "back_url") String back_url,
                             @RequestParam(value = "sign") String sign) {
        BusinessPlaceOrderParam param=new BusinessPlaceOrderParam();
        param.setUserid(userid);
        param.setProductid(productid);
        param.setPrice(price);
        param.setNum(num);
        param.setMobile(mobile);
        param.setSpordertime(spordertime);
        param.setSporderid(sporderid);
        param.setBack_url(back_url);
//        param.setKey(key);
        param.setSign(sign);
        try {
            String pattern = "^1[3456789]\\d{9}$";
            boolean matches = Pattern.matches(pattern, param.getMobile());
            if(!matches){
                throw new RuntimeException("充值号码，校验不同过请检查是否是手机号");
            }
            Object o = redisUtil.get("blacklist:"+param.getMobile());
            if(o!=null){
                throw new RuntimeException(param.getMobile()+"已被拉入黑名单，请24小小时后尝试。");
            }
//            String nowSign = param.MD5Sign();
//            if(!nowSign.equals(param.getSign())){
//                throw new RuntimeException("加密密匙不一致");
//            }
            QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(BusinessUser::getCode,param.getUserid());
            BusinessUser user = businessUserService.getOne(wrapper);
            if(ObjectUtils.isEmpty(user)){
                throw new RuntimeException("代理用户不存在");
            }
            if(!ControlUtils.isNotEmpty(user.getSecretKey())){
                throw new RuntimeException("代理用户未生成密匙");
            }
//            if(!user.getSecretKey().equals(param.getKey())){
//                throw new RuntimeException("代理用户的密匙不一致");
//            }
            QueryWrapper<BusinessGoods> goodsWrapper=new QueryWrapper<>();
            goodsWrapper.lambda().eq(BusinessGoods::getCode,param.getProductid());
            BusinessGoods goods = businessGoodsService.getOne(goodsWrapper);
            if(ObjectUtils.isEmpty(goods)){
                throw new RuntimeException("商品不存在");
            }
            if(param.getPrice()!=goods.getAmount().intValue()){
                throw new RuntimeException("商品价格与充值价格不一致");
            }
            BusinessOrder order = service.placeOrder(goods, user, param);
            Map<String, Object> map = new HashMap<>();
            map.put("orderid",order.getCode());
            map.put("productid",order.getGoodsCode());
            map.put("num",1);
            map.put("ordercash",order.getGoodsAmount());
            map.put("productname",order.getGoodsName());
            map.put("mobile",order.getRechargeAccount());
            map.put("resultno",0);
            map.put("fundbalance",user.getAmount());
            String xml =FormatUtil.mapToXML(map,"order");
            return xml;
        }catch (Exception e){
            e.printStackTrace();
            blacklistService.add(param.getMobile());
            throw new RuntimeException(e.getMessage());
        }
    }

    @PostMapping(value = "/getOrder")
    @ApiOperation(value = "用户-订单查询接口")
    public String getOrder(@RequestParam(value = "userid") String userid,
                           @RequestParam(value = "sporderid") String sporderid,
                           @RequestParam(value = "sign") String sign) {
//        String nowSign = param.MD5Sign();
//        if(!nowSign.equals(param.getSign())){
//            throw new RuntimeException("加密密匙不一致");
//        }
        QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(BusinessUser::getCode,userid);
        BusinessUser user = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("代理用户不存在");
        }
        if(!ControlUtils.isNotEmpty(user.getSecretKey())){
            throw new RuntimeException("代理用户未生成密匙");
        }
//        if(!user.getSecretKey().equals(key)){
//            throw new RuntimeException("代理用户的密匙不一致");
//        }
        QueryWrapper<BusinessOrder> orderQueryWrapper=new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(BusinessOrder::getUserOrderCode,sporderid);
        BusinessOrder order = service.getOne(orderQueryWrapper);
        if(ObjectUtils.isEmpty(order)){
            throw new RuntimeException("【"+sporderid+"】订单号的订单不存在，请检查");
        }
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("code",order.getCode());
            map.put("rechargeAccount",order.getRechargeAccount());
            map.put("goodsCode",order.getGoodsCode());
            map.put("goodsName",order.getGoodsName());
            map.put("goodsAmount",order.getGoodsAmount());
            map.put("state",order.getState());
            map.put("payState",order.getPayState());
            map.put("businessUserCode",order.getBusinessUserCode());
            map.put("businessUserNike",order.getBusinessUserNike());
            map.put("remake",order.getRemake());
            String xml =FormatUtil.mapToXML(map,"order");
            return xml;
        }catch (Exception exception){
            throw new RuntimeException(exception.getMessage());
        }
    }


    @PostMapping(value = "/getUserAmount")
    @ApiOperation(value = "用户-余额查询")
    public String getUserAmount(@RequestParam(value = "userid") String userid,
                                @RequestParam(value = "sign") String sign) {
        //        String nowSign = param.MD5Sign();
//        if(!nowSign.equals(param.getSign())){
//            throw new RuntimeException("加密密匙不一致");
//        }
        QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(BusinessUser::getCode,userid);
        BusinessUser user = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("代理用户不存在");
        }
        if(!ControlUtils.isNotEmpty(user.getSecretKey())){
            throw new RuntimeException("代理用户未生成密匙");
        }
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("code",user.getCode());
            map.put("name",user.getUserName());
            map.put("amount",user.getAmount());
            map.put("creditAmount",user.getCreditAmount());
            String xml =FormatUtil.mapToXML(map,"user");
            return xml;
        }catch (Exception exception){
            throw new RuntimeException(exception.getMessage());
        }
    }


//    @PostMapping(value = "/test-placeOrder")
//    @ApiOperation(value = "测试-下单接口")
//    public Result testCreateOrder(@RequestBody BusinessPlaceOrderParam item) {
//        String url="http://127.0.0.1:8088//business/user-api/placeOrderOutside";
//        try {
//            item.setTimeStamp(System.currentTimeMillis());
//            item.setSign(item.MD5Sign());
//            String  responseBody= HttpUtil.odPost(url, item,"");
//            return Result.success(responseBody);
//        }catch (Exception e){
//            e.printStackTrace();
//            throw new RuntimeException("");
//        }
//    }
//
//
//    @PostMapping(value = "/test-userReturnInterface")
//    @ApiOperation(value = "测试-用户下单回调")
//    public String userReturnInterface(@RequestBody Map<String,Object> param) {
//        System.out.println(param.toString());
//        return "ok";
//    }


}

